/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2012-2019. All rights reserved.
 */

package com.guchenbo.hive;

import lombok.extern.slf4j.Slf4j;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.security.UserGroupInformation;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;

/**
 * JDBCExample
 *
 * @author
 * @since 8.0.0
 */
@Slf4j
public class JDBCKerberosExample {

    public static final String HADOOP_SECURITY_AUTHENTICATION = "hadoop.security.authentication";
    public static final String HADOOP_SECURITY_AUTHENTICATION_VALUE = "kerberos";
    private static final String HIVE_DRIVER = "org.apache.hive.jdbc.HiveDriver";

    public static void main(String[] args) throws Exception {
        String principal = "simba-os";
        String keytab = "/Users/guchenbo/opt/etc/kerberos/dev02/keytab/simba-os.keytab";
        String krb5Conf = "/etc/krb5.conf";
        loginKerberos(principal, keytab, krb5Conf);

        String jdbcPrincipal = "hive/dev-02-datakun-startdt-2@EXAMPLE.COM";
        Class.forName(HIVE_DRIVER);
        String jdbcUrl = "jdbc:hive2://172.31.1.26:10000/;principal=" + jdbcPrincipal;
        Connection connection = DriverManager.getConnection(jdbcUrl);
        System.out.println(connection);
    }

    public static void loginKerberos(String principal, String keytab, String krb5Conf) throws IOException {
        System.setProperty("java.security.krb5.conf", krb5Conf);

        Configuration conf = new Configuration();
        conf.set(HADOOP_SECURITY_AUTHENTICATION, HADOOP_SECURITY_AUTHENTICATION_VALUE);
        UserGroupInformation.setConfiguration(conf);
        UserGroupInformation.loginUserFromKeytab(principal, keytab);
        System.out.println(UserGroupInformation.getLoginUser());
    }

}
